<?php

namespace App\Http\Controllers\Wallet;

use App\Helper\Functions;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Http\Models\AgencyAddress;
use App\Http\Models\AgencyOrder;

class IndexController extends Controller
{	
	private $walletHost;
	private $walletKey;
	
	function __construct()
	{
	    $this->walletHost = config('services.extend.walletHost');
		$this->walletKey = config('services.extend.walletKey');
	}
	
	// 获取钱包账户信息
	public function getAccountInfo($token){

		$userInfo = $this->getUserInfoFromToken($token);
		
		$getInfoUrl = $this->walletHost."/api/wallet/getUserAccount?wCode={$this->walletKey}&uId={$userInfo['uCode']}";
		
		$Functions = new Functions();
		$accountInfo = $Functions->Get($getInfoUrl);
		$accountInfo = json_decode($accountInfo, true);
		
		$knightInfo = DB::table('knight')->where('uId', $userInfo['uCode'])->first();
		$accountInfo['knight'] = $knightInfo;
		
		return json_encode($accountInfo);
	}
	
	// 获取钱包流水
	public function getTradeList($token){

		$userInfo = $this->getUserInfoFromToken($token);
		
		$getInfoUrl = $this->walletHost."/api/wallet/getTradeList?wCode={$this->walletKey}&uId={$userInfo['uCode']}"; //&wtType=charge/consume
		
		$Functions = new Functions();
		$accountInfo = $Functions->Get($getInfoUrl);

		return $accountInfo;
	}
	
	// 提交提现申请
	public function applyWithdraw(Request $request){
		
		$token = $request->token;
		$money = $request->money;
		
		$userInfo = $this->getUserInfoFromToken($token);
		
		$accountInfo = $this->getAccountInfo($token);
		$accountInfo = json_decode($accountInfo, true);
		$accountInfo = $accountInfo['data'];
		
		if (!is_numeric($money)){
			return $this->returnMsg(0, '请求非法');
		}
		
		if ($money <= 0){
			return $this->returnMsg(0, '请求非法');
		}
		
		if ($accountInfo['waMoney'] < $money){
			return $this->returnMsg(0, '账户余额不足');
		}
		
		// 判断是否有尚未审核的申请
		$checkInfo = DB::table('wallet_withdraw')->where('uId', $userInfo['uCode'])->where('wwIsCheck', 0)->first();
		if (!empty($checkInfo)){
			return $this->returnMsg(0, '无法提交，上一个申请没有审核');
		}
		
		$knightInfo = DB::table('knight')->where('uId', $userInfo['uCode'])->first();
		$wwPledge = 0;
		$uType = 'user';
		if (!empty($knightInfo)){
			$wwPledge = $knightInfo->kPledge;
			$uType = 'knight';
		}
		DB::table('wallet_withdraw')->insert(
			[
				'uId' => $userInfo['uCode'], 
				'wwMoney' => $money, 
				'wwAccountMoney' => $accountInfo['waMoney'],
				'wwPledge' => $wwPledge,
				'uType' => $uType
			]
		);
		
		return $this->returnMsg(1, '申请成功，将在2个工作日内到账');
	}
}
